package com.caiwangdai.app.origin.back

import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v4.app.FragmentManager


class BackHandlerHelper {

    companion object {
        /**
         * 将back事件分发给 FragmentManager 中管理的子Fragment，如果该 FragmentManager 中的所有Fragment都
         * 没有处理back事件，则尝试 FragmentManager.popBackStack()

         * @return 如果处理了back键则返回 **true**
         * *
         * @see .handleBackPress
         * @see .handleBackPress
         */
        private fun handleBackPress(fragmentManager: FragmentManager): Boolean {
            if (fragmentManager.backStackEntryCount < 1) return false
            for (i in 0..fragmentManager.backStackEntryCount - 1) {
                val child = fragmentManager.getBackStackEntryAt(i) as Fragment
                if (isFragmentBackHandled(child)) {
                    return true
                }
            }
            if (fragmentManager.backStackEntryCount > 0) {
                fragmentManager.popBackStack()
                return true
            }
            return false
        }

        fun handleBackPress(fragment: Fragment): Boolean {
            return handleBackPress(fragment.childFragmentManager)
        }

        fun handleBackPress(fragmentActivity: FragmentActivity): Boolean {
            return handleBackPress(fragmentActivity.supportFragmentManager)
        }

        /**
         * 判断Fragment是否处理了Back键

         * @return 如果处理了back键则返回 **true**
         */
        fun isFragmentBackHandled(fragment: Fragment?): Boolean {
            return fragment != null
                    && fragment.isVisible
                    && fragment.userVisibleHint //for ViewPager

                    && fragment is FragmentBackHandler
                    && fragment.onBackPressed()
        }
    }
}